package remind;

import models.BaseModel;
import models.constants.DeletedStatus;
import play.db.jpa.JPA;

import javax.persistence.*;
import java.util.*;
import java.util.List;

/**
 * 时间到期提醒
 * Created by buhaoba on 2016/10/20.
 */
@Entity
@Table(name = "time_reminds")
public class TimeRemind extends BaseModel {

    /**
     * 文件名称
     */
    @Column(name = "name")
    public String name;

    /**
     *  文件类型
     */
    @JoinColumn(name = "time_remind_type_id")
    @ManyToOne
    public TimeRemindType timeRemindType;

    /**
     * 结束时间
     */
    public Date endAt;
    /**
     * 提前多少天提醒
     * days 为天数
     */
    public Integer days;
    /**
     * 剩余天数
     * days 为天数
     */
    public Integer redays;

    //备注
    public String remark;

    public  Boolean mark;

    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;


    //根据id查找得到TimeRemind'
    public static List<TimeRemind> findByTimeRemindId(long id){

        return TimeRemind.find("id=? and deleted=?",id,DeletedStatus.UN_DELETED).fetch();

    }
    public static TimeRemind findByTimeRemind(long id){

        return TimeRemind.find("id=? and deleted=?",id,DeletedStatus.UN_DELETED).first();

    }
    public static void updataTimeRemindRedays(){
        //更新的sql的写法
                String sql="update time_reminds t set  t.mark = 1,t.redays= TIMESTAMPDIFF(Day,str_to_date(NOW(),'%Y-%m-%d %H:%i:%s'),t.endAt)  where TIMESTAMPDIFF(Day,str_to_date(NOW(),'%Y-%m-%d %H:%i:%s'),t.endAt)<t.days;";
                JPA.em().createNativeQuery(sql).executeUpdate();
        }

    public static void updataRedays(){
        //更新的sql的写法
        String sql="update time_reminds t set t.redays= TIMESTAMPDIFF(Day,str_to_date(NOW(),'%Y-%m-%d %H:%i:%s'),t.endAt)";
        JPA.em().createNativeQuery(sql).executeUpdate();
    }
}